#!/usr/bin/env python
#coding=utf-8

'''Validate taobao user'''

import md5
import base64
import TaobaoApiDemo

def validate_top_sign(top_sign, top_appkey, top_parameters, top_session, app_secret):
    '''validate top_sign'''
    #top_sign = base64(md5(top_appkey+top_parameters+top_session+app_secret))
    
    sign = top_appkey + top_parameters + top_session + app_secret
    sign = md5.new(sign).digest()
    sign = base64.b64encode(sign)
    
    return cmp(top_sign, sign) == 0

def validate_sessionkey(top_appkey, top_session, parameters, app_secret):
    '''validate sessionkey'''
    nick = parameters[parameters.rfind('=') + 1:]
    paramDict = {
        'app_key': top_appkey,
        'method': 'taobao.user.get',
        'fields': 'created,type',
        'nick': nick,
        'session': top_session
    }
    
    #调用taobao api，获取用户信息
    apiResult = TaobaoApiDemo.getResult(paramDict, app_secret)
    try:
        apiResult['user_get_response']['user']['type']
        return True
    except:
        return False

def validate_login(parameters):
    '''validate log in or not'''
    return parameters.find('visitor_id') != -1
    
def getID(parameters):
    '''get user id'''
    return parameters[parameters.find('visitor_id')+11:parameters.find('visitor_nick')-1]

def validate(queryString, app_secret):
    '''top_appkey=12034368&
    top_parameters=aWZyYW1lPTEmdHM9MTI2OTYwMzU5MjcwOSZ2aWV3X21vZGU9ZnVsbCZ2aWV3X3dpZHRoPTAmdmlzaXRvcl9pZD02NTc1MzA1NSZ2aXNpdG9yX25pY2s9YWxpcHVibGljMDI%3D&
    top_session=23055d2aee64fceb05789cfa14beddfef7c2f&
    top_sign=%2BSybXVsp9W3zJ9%2FdSppiIA%3D%3D'''

    top_appkey = ''
    top_parameters = ''
    top_session = ''
    top_sign = ''
    
    #for flex
    queryString = queryString.replace('%3D', '=')
    queryString = queryString.replace('%2B', '+')
    queryString = queryString.replace('%2F', '/')
    
    #获得各项参数
    querys = queryString.split('&')
    for query in querys:
        if query.find('top_appkey') != -1:
            top_appkey = query[query.find('=') + 1:]
        elif query.find('top_parameters') != -1:
            top_parameters = query[query.find('=') + 1:]
        elif query.find('top_session') != -1:
            top_session = query[query.find('=') + 1:]
        elif query.find('top_sign') != -1:
            top_sign = query[query.find('=') + 1:]

    #判断是否正确取得各参数
    if top_appkey == '':
        return 'Err: Lack of top_appkey!'
    if top_parameters == '':
        return 'Err: Lack of top_parameters!'
    if top_session == '':
        return 'Err: Lack of top_session!'
    if top_sign == '':
        return 'Err: Lack of top_sign!'
    
    #验证top_sign
    if validate_top_sign(top_sign, top_appkey, top_parameters, top_session, app_secret) == False:
        return 'Err: top_sign invalid!'
    
    parameters = base64.b64decode(top_parameters)
    
    #验证sessionkey
    if validate_sessionkey(top_appkey, top_session, parameters, app_secret) == False:
        return 'Err: sessionkey invalid!'
    
    #验证是否登录
    if validate_login(parameters) == False:
        return 'Err: Please login!'
    
    #验证通过，返回提示信息和用户id
    return 'Validate Success!' + getID(parameters)